import os
import cgi
import datetime
import urllib
import wsgiref.handlers
from lib import tags
from lib import datastore

#standard appengine modules
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.api import images
from google.appengine.api import users
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

#blobstore modules
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers

class Engine(webapp.RequestHandler):
    
    def welcome_page(self, values):
        
        greeting = (users.create_login_url("/"))
        values["login"] = greeting
        path = os.path.join(os.path.dirname(__file__), 'welcome.html')
        self.response.out.write(template.render(path, values))    
    
    def main_page(self, values, user):
    
        nickname = user.nickname()
        user_id = user.user_id()
        greeting = ("Welcome, %s! (<a href=\"%s\">sign out</a>)" %
                    (nickname, users.create_logout_url("/logout/")))
    
        userImages = db.GqlQuery("SELECT * FROM Photo WHERE ownerID = :1 ORDER BY upload_date DESC", user_id)
        if userImages:
            values["userImages"] = userImages
        values["greeting"] = greeting
        
        path = os.path.join(os.path.dirname(__file__), 'main.html')
        self.response.out.write(template.render(path, values))        
  
    def get(self):
        
        values = {}
        user = users.get_current_user()
        if not user:
            self.welcome_page(values)
        else:
            self.main_page(values, user)
        
class ViewHandler(webapp.RequestHandler):
    '''View the image in full and renders image options '''
    
    def get(self, key):
    
        values = {}
        user = users.get_current_user()
        image = datastore.get_photo(self, key)
        if image:
            values["image"] = image
            values["tags"] = image.tags.split()
            values["owner"] = image.ownerID == user.user_id()
        path = os.path.join(os.path.dirname(__file__), 'view.html')
        self.response.out.write(template.render(path, values))

class BrowseHandler(webapp.RequestHandler):
    '''Displays a gallery'''
    
    def get(self, temp):
        
        values = {}
        imageKeys = []
        searchTag = self.request.get('tag')
        if searchTag:
            searchTag = searchTag.lower() #normalize it to lower case
            images = db.GqlQuery("SELECT * FROM Tag WHERE name = :1", searchTag)
            for image in images:
                imageKeys.append(image.imageKey)
            values["tag"] = searchTag
        else:
            images = db.GqlQuery("SELECT * FROM Photo ORDER BY upload_date DESC")
            for image in images:
                imageKeys.append(str(image.key()))
        values["imageKeys"] = imageKeys
        path = os.path.join(os.path.dirname(__file__), 'browse.html')
        self.response.out.write(template.render(path, values)) 

class ErrorHandler(webapp.RequestHandler):
    '''Should display useful error messages to the user'''
    
    def get(self, values):
        path = os.path.join(os.path.dirname(__file__), 'error.html')
        self.response.out.write(template.render(path, values))
        
class LogoutHandler(webapp.RequestHandler):
    '''Process requests upon logging out'''
    
    def get(self, values):
        
        values = {}
        path = os.path.join(os.path.dirname(__file__), 'logout.html')
        self.response.out.write(template.render(path, values))
        
class HelpHandler(webapp.RequestHandler):
    '''Displays the help page'''
    
    def get(self):
            
        path = os.path.join(os.path.dirname(__file__), 'about.html')
        self.response.out.write(template.render(path, {}))    
        
def main():
    paths = [('/upload', datastore.UploadHandler),
             ('/view/([^/]+)?', ViewHandler),
             ('/browse/([^/]+)?', BrowseHandler),             
             ('/error/([^/]+)?', ErrorHandler),
             ('/logout/([^/]+)?', LogoutHandler),
             ('/thumb/([^/]+)?', datastore.ThumbHandler),
             ('/image/([^/]+)?', datastore.ServeHandler),
             ('/update/([^/]+)?', datastore.UpdateHandler),
             ('/tag/([^/]+)?', tags.TagHandler),
             ('/about.html', HelpHandler),
             ('/.*', Engine)
             ]
    application = webapp.WSGIApplication(paths, debug=True)  
    run_wsgi_app(application)

if __name__ == '__main__':
    main()